import string
from random import choices
from django.db.models import Q, Sum, Avg
from django.shortcuts import render, redirect, get_object_or_404
from django.contrib.auth.decorators import login_required
from django.contrib import messages
from django.conf import settings
from django.core.cache import cache
from django.core.mail import send_mail
from django.shortcuts import render, redirect
from django.contrib.auth import login, authenticate, logout
from django.http import JsonResponse, request
from django.urls import reverse
from django.utils import timezone
from django.views.decorators.csrf import csrf_exempt
from django.views.decorators.http import require_POST, require_http_methods

from . import models
from .models import CustomUser, UserProfile, Follow
from Location.models import Event, EventRegistration, EventReview, EventDiscussion, PointTransaction, CommunityPost

from django.contrib.admin.views.decorators import staff_member_required
from django.contrib.auth.decorators import user_passes_test


def is_superuser(user):
    """检查用户是否是超级管理员"""
    return user.is_authenticated and user.is_superuser


from django.contrib.auth import authenticate, login
from django.http import JsonResponse
from django.shortcuts import render, redirect
from .models import CustomUser
import re


def login_view(request):
    if request.method == 'POST':
        username_or_email = request.POST.get('username', '').strip()
        password = request.POST.get('password')
        is_ajax = request.headers.get('X-Requested-With') == 'XMLHttpRequest'

        # 验证输入
        if not username_or_email or not password:
            return handle_response(is_ajax,
                                   error='请输入用户名/邮箱和密码',
                                   template='login.html')

        # 验证用户名/邮箱格式
        if not validate_username_or_email(username_or_email):
            return handle_response(is_ajax,
                                   error='请输入有效的用户名或邮箱地址',
                                   template='login.html')

        # 认证用户
        user = authenticate_user(username_or_email, password, request)

        if user is not None:
            return handle_success_login(request, user, is_ajax)
        else:
            return handle_response(is_ajax,
                                   error='用户名/邮箱或密码错误',
                                   template='login.html')

    return render(request, 'login.html')


def authenticate_user(username_or_email, password, request):
    """认证用户，支持用户名或邮箱"""
    if is_email(username_or_email):
        # 邮箱登录
        try:
            user_obj = CustomUser.objects.get(email=username_or_email)
            return authenticate(request, username=user_obj.username, password=password)
        except CustomUser.DoesNotExist:
            return None
    else:
        # 用户名登录
        return authenticate(request, username=username_or_email, password=password)


def handle_success_login(request, user, is_ajax):
    """处理成功登录"""
    login(request, user)

    # 根据用户类型确定重定向URL
    if user.is_superuser:
        redirect_url = '/customer/admin-dashboard/'
        success_msg = '登录成功！即将进入管理员面板'
    else:
        redirect_url = '/location/index/'
        success_msg = '登录成功！即将进入首页'

    if is_ajax:
        return JsonResponse({
            'success': True,
            'message': success_msg,
            'redirect_url': redirect_url,
            'is_superuser': user.is_superuser
        })
    else:
        return redirect(redirect_url)


def handle_response(is_ajax, error=None, success=None, template=None, context=None):
    """统一处理响应"""
    if is_ajax:
        if error:
            return JsonResponse({'success': False, 'message': error})
        else:
            return JsonResponse({'success': True, 'message': success})
    else:
        if template:
            ctx = context or {}
            if error:
                ctx['error'] = error
            if success:
                ctx['success'] = success
            return render(request, template, ctx)


def is_email(input_str):
    """判断输入是否为邮箱格式"""
    email_pattern = r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$'
    return re.match(email_pattern, input_str) is not None


def validate_username_or_email(input_str):
    """验证用户名或邮箱格式"""
    # 用户名规则：字母、数字、下划线，长度3-20
    username_pattern = r'^[a-zA-Z0-9_]{3,20}$'

    # 邮箱验证规则
    email_pattern = r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$'

    return re.match(username_pattern, input_str) is not None or re.match(email_pattern, input_str) is not None

def register_view(request):
    if request.method == 'POST':
        username = request.POST.get('username')
        email = request.POST.get('email')
        password = request.POST.get('password')
        password_confirm = request.POST.get('password_confirm')

        # 验证密码是否匹配
        if password != password_confirm:
            if request.headers.get('X-Requested-With') == 'XMLHttpRequest':
                return JsonResponse({'success': False, 'message': '两次输入的密码不匹配'})
            return render(request, 'register.html', {'error': '两次输入的密码不匹配'})

        # 检查用户名是否已存在
        if CustomUser.objects.filter(username=username).exists():
            if request.headers.get('X-Requested-With') == 'XMLHttpRequest':
                return JsonResponse({'success': False, 'message': '用户名已存在'})
            return render(request, 'register.html', {'error': '用户名已存在'})

        # 检查邮箱是否已存在
        if CustomUser.objects.filter(email=email).exists():
            if request.headers.get('X-Requested-With') == 'XMLHttpRequest':
                return JsonResponse({'success': False, 'message': '邮箱已被注册'})
            return render(request, 'register.html', {'error': '邮箱已被注册'})

        # 创建用户
        try:
            user = CustomUser.objects.create_user(
                username=username,
                email=email,
                password=password,
                user_type='normal'
            )

            # 自动登录
            login(request, user)
            if request.headers.get('X-Requested-With') == 'XMLHttpRequest':
                return JsonResponse({'success': True, 'message': '注册成功'})
            # 修正重定向路径
            return redirect('location:index')

        except Exception as e:
            if request.headers.get('X-Requested-With') == 'XMLHttpRequest':
                return JsonResponse({'success': False, 'message': f'注册失败: {str(e)}'})
            return render(request, 'register.html', {'error': f'注册失败: {str(e)}'})

    return render(request, 'register.html')


def forgot_password_view(request):
    if request.method == 'POST':
        email = request.POST.get('email')
        verification_code = request.POST.get('verification_code')
        new_password = request.POST.get('new_password')
        confirm_password = request.POST.get('confirm_password')

        try:
            user = CustomUser.objects.get(email=email)

            # 验证验证码
            cached_code = cache.get(f'verification_code_{email}')
            if not cached_code or cached_code != verification_code:
                if request.headers.get('X-Requested-With') == 'XMLHttpRequest':
                    return JsonResponse({'success': False, 'message': '验证码错误或已过期'})
                return render(request, 'forgot_password.html', {'error': '验证码错误或已过期'})

            # 验证密码
            if new_password != confirm_password:
                if request.headers.get('X-Requested-With') == 'XMLHttpRequest':
                    return JsonResponse({'success': False, 'message': '两次输入的密码不匹配'})
                return render(request, 'forgot_password.html', {'error': '两次输入的密码不匹配'})

            if len(new_password) < 4:
                if request.headers.get('X-Requested-With') == 'XMLHttpRequest':
                    return JsonResponse({'success': False, 'message': '密码长度至少为4位'})
                return render(request, 'forgot_password.html', {'error': '密码长度至少为4位'})

            # 更新密码并清除验证码
            user.set_password(new_password)
            user.save()
            cache.delete(f'verification_code_{email}')

            if request.headers.get('X-Requested-With') == 'XMLHttpRequest':
                return JsonResponse({'success': True, 'message': '密码重置成功'})
            return render(request, 'login.html', {'success': '密码重置成功，请重新登录'})

        except CustomUser.DoesNotExist:
            if request.headers.get('X-Requested-With') == 'XMLHttpRequest':
                return JsonResponse({'success': False, 'message': '该邮箱未注册'})
            return render(request, 'forgot_password.html', {'error': '该邮箱未注册'})

    return render(request, 'forgot_password.html')


@csrf_exempt
def send_verification_code(request):
    if request.method == 'POST':
        email = request.POST.get('email')

        # 检查邮箱是否存在
        if not CustomUser.objects.filter(email=email).exists():
            return JsonResponse({'success': False, 'message': '该邮箱未注册'})

        # 生成验证码
        code = generate_verification_code()

        # 存储到缓存（5分钟有效期）
        cache.set(f'verification_code_{email}', code, 300)

        # 发送邮件
        try:
            send_mail(
                '本地有约 - 密码重置验证码',
                f'您的验证码是：{code}，有效期为5分钟。',
                settings.DEFAULT_FROM_EMAIL,
                [email],
                fail_silently=False,
            )
            return JsonResponse({'success': True, 'message': '验证码已发送到您的邮箱'})
        except Exception as e:
            return JsonResponse({'success': False, 'message': '邮件发送失败'})

    return JsonResponse({'success': False, 'message': '请求方法错误'})


def logout_view(request):
    logout(request)
    return redirect('customer:login')

def generate_verification_code(length=6):
    """生成随机验证码"""
    return ''.join(choices(string.digits, k=length))

@login_required
def profile(request):
    """个人中心"""
    user = request.user
    user.refresh_from_db()

    print(f"DEBUG: 用户 {user.username} 的积分 = {user.points}")

    # 统计信息
    following_count = Follow.objects.filter(follower=user).count()
    followers_count = Follow.objects.filter(following=user).count()
    events_attended = EventRegistration.objects.filter(user=user).count()
    events_organized = Event.objects.filter(organizer=user).count()
    reviews_count = EventDiscussion.objects.filter(user=user, is_deleted=False).count()

    # 获取草稿数据 - 修正查询条件
    my_drafts_list = Event.objects.filter(organizer=user, status='draft').order_by('-created_at')
    drafts_count = my_drafts_list.count()

    print(f"DEBUG: 草稿数量: {drafts_count}")
    for draft in my_drafts_list:
        print(f"DEBUG: 草稿 - ID: {draft.id}, 标题: {draft.title}, 状态: {draft.status}")

    # 获取积分汇总
    from Location.services import PointService
    point_summary = PointService.get_user_points_summary(user)

    # 最近的数据
    recent_events = EventRegistration.objects.filter(user=user).select_related('event').order_by('-registration_time')[:5]
    recent_posts = CommunityPost.objects.filter(author=user, is_active=True).order_by('-created_at')[:5]
    recent_points = PointTransaction.objects.filter(user=user).order_by('-created_at')[:5]

    # 为标签页准备完整数据
    my_events_list = Event.objects.filter(organizer=user).exclude(status='draft').order_by('-created_at')
    my_registrations_list = EventRegistration.objects.filter(user=user).select_related('event').order_by('-registration_time')
    my_reviews_list = EventDiscussion.objects.filter(user=user, is_deleted=False).select_related('event').order_by('-created_at')
    transactions = PointTransaction.objects.filter(user=user).order_by('-created_at')[:50]

    context = {
        'user': user,
        'following_count': following_count,
        'followers_count': followers_count,
        'events_attended': events_attended,
        'events_organized': events_organized,
        'reviews_count': reviews_count,
        'drafts_count': drafts_count,
        'recent_events': recent_events,
        'recent_posts': recent_posts,
        'recent_points': recent_points,
        'my_events_list': my_events_list,
        'my_registrations_list': my_registrations_list,
        'my_reviews_list': my_reviews_list,
        'transactions': transactions,
        'total_earned': point_summary.get('total_earned', 0),
        'total_spent': point_summary.get('total_spent', 0),
        'drafts': my_drafts_list,  # 确保使用 'drafts' 作为变量名
    }

    return render(request, 'profile.html', context)
@login_required
def privacy_settings(request):
    """处理隐私设置"""
    if request.method == 'POST':
        try:
            user = request.user

            print(f"=== 更新隐私设置 ===")
            print(f"用户: {user.username}")

            # 只更新这三个隐私设置
            user.show_email = request.POST.get('show_email') == 'on'
            user.show_phone = request.POST.get('show_phone') == 'on'
            user.show_location = request.POST.get('show_location') == 'on'
            user.save()

            print(f"隐私设置: 邮箱={user.show_email}, 电话={user.show_phone}, 位置={user.show_location}")

            messages.success(request, '隐私设置更新成功！')

        except Exception as e:
            print(f"更新隐私设置错误: {str(e)}")
            import traceback
            traceback.print_exc()
            messages.error(request, f'更新失败: {str(e)}')

    return redirect('customer:profile')


@login_required
def point_history(request):
    """积分明细"""
    transactions = PointTransaction.objects.filter(user=request.user).order_by('-created_at')

    # 统计
    total_earned = PointTransaction.objects.filter(
        user=request.user,
        transaction_type__in=['earn', 'refund']
    ).aggregate(total=Sum('points'))['total'] or 0

    total_spent = PointTransaction.objects.filter(
        user=request.user,
        transaction_type='spend'
    ).aggregate(total=Sum('points'))['total'] or 0

    # 获取用户的其他信息用于页面显示
    followers_count = Follow.objects.filter(following=request.user).count()
    following_count = Follow.objects.filter(follower=request.user).count()

    # 获取活动数据
    events_organized = Event.objects.filter(organizer=request.user).count()
    events_attended = EventRegistration.objects.filter(user=request.user).count()
    reviews_count = EventReview.objects.filter(user=request.user).count()

    context = {
        'user': request.user,
        'transactions': transactions,
        'total_earned': total_earned,
        'total_spent': total_spent,
        'followers_count': followers_count,
        'following_count': following_count,
        'events_organized': events_organized,
        'events_attended': events_attended,
        'reviews_count': reviews_count,
    }
    return render(request, 'profile.html', context)


@login_required
def my_events(request):
    """我发起的活动"""
    events = Event.objects.filter(organizer=request.user).order_by('-created_at')

    # 获取用户的其他信息用于页面显示
    followers_count = Follow.objects.filter(following=request.user).count()
    following_count = Follow.objects.filter(follower=request.user).count()
    events_attended = EventRegistration.objects.filter(user=request.user).count()
    reviews_count = EventReview.objects.filter(user=request.user).count()

    context = {
        'user': request.user,
        'my_events_list': events,  # 使用正确的变量名
        'events_organized': events.count(),
        'followers_count': followers_count,
        'following_count': following_count,
        'events_attended': events_attended,
        'reviews_count': reviews_count,
    }
    return render(request, 'profile.html', context)


@login_required
def my_registrations(request):
    """我报名的活动"""
    registrations = EventRegistration.objects.filter(
        user=request.user
    ).select_related('event').order_by('-registration_time')

    # 获取用户的其他信息用于页面显示
    followers_count = Follow.objects.filter(following=request.user).count()
    following_count = Follow.objects.filter(follower=request.user).count()
    events_organized = Event.objects.filter(organizer=request.user).count()
    reviews_count = EventReview.objects.filter(user=request.user).count()

    context = {
        'user': request.user,
        'my_registrations_list': registrations,  # 使用正确的变量名
        'events_attended': registrations.count(),
        'followers_count': followers_count,
        'following_count': following_count,
        'events_organized': events_organized,
        'reviews_count': reviews_count,
    }
    return render(request, 'profile.html', context)


@login_required
def my_reviews(request):
    """我的评价 - 显示我在活动详情页发表的所有评论"""
    print(f"=== 调试: my_reviews 视图被调用 ===")
    print(f"用户: {request.user.username} (ID: {request.user.id})")

    # 获取评论数据
    discussions = EventDiscussion.objects.filter(
        user=request.user,
        is_deleted=False
    ).select_related('event').order_by('-created_at')

    print(f"查询到的评论数量: {discussions.count()}")

    # 检查每条评论的数据
    for i, discussion in enumerate(discussions, 1):
        print(f"评论 {i}: ID={discussion.id}, 活动='{discussion.event.title}', 内容='{discussion.content}'")

    # 获取其他统计信息
    followers_count = Follow.objects.filter(following=request.user).count()
    following_count = Follow.objects.filter(follower=request.user).count()
    events_organized = Event.objects.filter(organizer=request.user).count()
    events_attended = EventRegistration.objects.filter(user=request.user).count()

    context = {
        'user': request.user,
        'my_reviews_list': discussions,
        'reviews_count': discussions.count(),
        'followers_count': followers_count,
        'following_count': following_count,
        'events_organized': events_organized,
        'events_attended': events_attended,
    }

    print(f"传递给模板的变量:")
    print(f"- my_reviews_list: {len(discussions)} 条记录")
    print(f"- reviews_count: {discussions.count()}")

    return render(request, 'profile.html', context)


@login_required
@require_POST
@csrf_exempt
def delete_my_comment(request, comment_id):
    """删除我的评论"""
    try:
        discussion = get_object_or_404(EventDiscussion, id=comment_id, user=request.user)

        # 软删除
        discussion.is_deleted = True
        discussion.deleted_at = timezone.now()
        discussion.save()

        return JsonResponse({'success': True, 'message': '评论删除成功'})

    except EventDiscussion.DoesNotExist:
        return JsonResponse({'success': False, 'message': '评论不存在'})
    except Exception as e:
        return JsonResponse({'success': False, 'message': f'删除失败: {str(e)}'})

@login_required
def my_posts(request):
    """我发布的帖子"""
    try:
        from Location.models import CommunityPost
        posts = CommunityPost.objects.filter(author=request.user).order_by('-created_at')

        context = {
            'posts': posts,
        }
        return render(request, 'my_posts.html', context)

    except ImportError:
        messages.error(request, '社区功能暂不可用')
        return redirect('customer:profile')


@login_required
def create_post(request):
    """创建新帖子"""
    if request.method == 'POST':
        try:
            from Location.models import CommunityPost

            title = request.POST.get('title')
            content = request.POST.get('content')
            post_type = request.POST.get('post_type', 'discussion')

            if not title or not content:
                messages.error(request, '标题和内容不能为空')
                return redirect('customer:create_post')

            post = CommunityPost.objects.create(
                title=title,
                content=content,
                post_type=post_type,
                author=request.user
            )

            messages.success(request, '帖子发布成功！')
            return redirect('customer:profile')

        except ImportError:
            messages.error(request, '社区功能暂不可用')
            return redirect('customer:profile')

    return render(request, 'create_post.html')

# 草稿
@login_required
def my_drafts(request):
    """我的草稿"""
    drafts = Event.objects.filter(organizer=request.user, status='draft').order_by('-created_at')
    context = {
        'drafts': drafts,
    }
    return render(request, 'my_drafts.html', context)


@login_required
@require_POST
@csrf_exempt
def cancel_registration(request):
    """取消活动报名 - 标记为取消状态"""
    try:
        event_id = request.POST.get('event_id')
        if not event_id:
            return JsonResponse({'success': False, 'message': '活动ID不能为空'})

        print(f"取消报名请求 - 用户: {request.user.username}, 活动ID: {event_id}")

        # 查找报名记录
        registration = EventRegistration.objects.get(
            event_id=event_id,
            user=request.user,
            status='registered'  # 只取消已报名的记录
        )

        # 将状态改为 cancelled
        registration.status = 'cancelled'
        registration.cancellation_time = timezone.now()
        registration.save()

        # 减少活动的当前参与人数
        event = registration.event
        if event.current_participants > 0:
            event.current_participants -= 1
            event.save()

        print(f"取消报名成功 - 活动: {event.title}")
        return JsonResponse({'success': True, 'message': '取消报名成功'})

    except EventRegistration.DoesNotExist:
        print(f"取消报名失败 - 未找到报名记录")
        return JsonResponse({'success': False, 'message': '未找到报名记录或已取消'})
    except Exception as e:
        print(f"取消报名异常: {str(e)}")
        return JsonResponse({'success': False, 'message': f'取消报名失败: {str(e)}'})

from Customer.oss_storage import CustomOssStorage


@login_required
def update_profile(request):
    """更新个人资料 - 直接使用自定义存储后端处理头像"""
    if request.method == 'POST':
        user = request.user

        try:
            print(f"=== 开始更新用户资料 ===")
            print(f"用户: {user.username}")

            # 更新 CustomUser 文本字段
            user.bio = request.POST.get('bio', '')
            user.interests = request.POST.get('interests', '')
            user.location = request.POST.get('location', '')
            user.phone = request.POST.get('phone', '')

            # 处理头像上传
            if 'avatar' in request.FILES:
                avatar_file = request.FILES['avatar']
                print(f"收到头像文件: {avatar_file.name}, 大小: {avatar_file.size} bytes")

                # 验证文件类型和大小
                allowed_types = ['image/jpeg', 'image/png', 'image/gif', 'image/webp']
                if avatar_file.content_type not in allowed_types:
                    messages.error(request, '只支持JPEG、PNG、GIF或WebP格式的图片')
                    return redirect('customer:profile')

                if avatar_file.size > 5 * 1024 * 1024:
                    messages.error(request, '头像文件大小不能超过5MB')
                    return redirect('customer:profile')

                # 使用自定义存储后端
                oss_storage = CustomOssStorage()

                # 生成唯一的文件名
                import uuid
                file_extension = avatar_file.name.split('.')[-1]
                oss_object_name = f"avatars/{user.id}_{uuid.uuid4().hex[:8]}.{file_extension}"

                print(f"准备上传到OSS: {oss_object_name}")

                # 删除旧头像（如果存在）
                if user.avatar and user.avatar.name:
                    try:
                        print(f"删除旧头像: {user.avatar.name}")
                        oss_storage.delete(user.avatar.name)
                    except Exception as e:
                        print(f"删除旧头像错误: {e}")

                # 上传到OSS
                avatar_file.seek(0)
                saved_name = oss_storage.save(oss_object_name, avatar_file)
                print(f"✅ OSS上传成功: {saved_name}")

                # 直接设置文件名，避免使用FileField的保存逻辑
                user.avatar.name = saved_name

                # 手动更新数据库
                from django.db import connection
                with connection.cursor() as cursor:
                    cursor.execute(
                        "UPDATE customer_customuser SET avatar = %s WHERE id = %s",
                        [saved_name, user.id]
                    )
                print("✅ 数据库更新成功")

            else:
                # 如果没有上传新头像，正常保存
                user.save()
                print("✅ 用户信息保存成功（无头像更新）")

            # 更新 UserProfile 字段
            try:
                profile, created = UserProfile.objects.get_or_create(user=user)
                print(f"获取UserProfile: 已创建={created}")

                # 更新 UserProfile 字段
                profile.gender = request.POST.get('gender', '')

                # 处理生日字段
                birth_date_str = request.POST.get('birth_date', '')
                if birth_date_str:
                    try:
                        from datetime import datetime
                        profile.birth_date = datetime.strptime(birth_date_str, '%Y-%m-%d').date()
                        print(f"设置生日: {profile.birth_date}")
                    except ValueError as e:
                        print(f"生日格式错误: {birth_date_str}, 错误: {e}")
                        # 如果日期格式错误，保持原值
                else:
                    profile.birth_date = None
                    print("清空生日")

                profile.occupation = request.POST.get('occupation', '')
                profile.wechat_id = request.POST.get('wechat_id', '')

                profile.save()
                print("✅ UserProfile 保存成功")
                print(f"UserProfile 数据: 性别={profile.gender}, 职业={profile.occupation}, 微信号={profile.wechat_id}")

            except Exception as e:
                print(f"❌ 更新 UserProfile 错误: {e}")
                import traceback
                traceback.print_exc()
                # 不阻止整个更新流程，只是记录错误

            messages.success(request, '个人资料更新成功！')
            print("=== 更新完成 ===")

        except Exception as e:
            print(f"❌ 更新个人资料错误: {e}")
            import traceback
            traceback.print_exc()
            messages.error(request, f'更新失败: {str(e)}')

        return redirect('customer:profile')

    return redirect('customer:profile')

# ==================== 管理员相关视图 ====================
@user_passes_test(is_superuser)
def admin_dashboard(request):
    """管理员仪表板"""
    # 获取统计数据
    total_users = CustomUser.objects.count()
    total_events = Event.objects.filter(status__in=['published', 'rejected']).count()
    total_registrations = EventRegistration.objects.count()
    pending_events_count = Event.objects.filter(status='pending').count()  # 待审核活动数量

    # 获取最近数据用于初始显示
    recent_users = CustomUser.objects.order_by('-date_joined')[:5]
    recent_events = Event.objects.order_by('-created_at')[:5]
    pending_events = Event.objects.filter(status='pending').order_by('-created_at')[:5]

    context = {
        'total_users': total_users,
        'total_events': total_events,
        'total_registrations': total_registrations,
        'pending_events_count': pending_events_count,
        'recent_users': recent_users,
        'recent_events': recent_events,
        'pending_events': pending_events,
    }

    return render(request, 'admin_dashboard.html', context)

@login_required
@require_POST
def grant_points_for_event(request, event_id):
    """为已发布活动发放积分"""
    try:
        print(f"🔍 [积分发放] 开始处理活动积分发放，活动ID: {event_id}")

        # 获取活动对象
        from Location.models import Event, PointTransaction
        event = Event.objects.get(id=event_id)

        print(f"🔍 [积分发放] 活动: {event.title}, 状态: {event.status}, 组织者: {event.organizer.username}")

        # 检查活动状态 - 必须是已发布状态
        if event.status != 'published':
            return JsonResponse({
                'success': False,
                'message': f'活动未发布，当前状态: {event.get_status_display()}'
            })

        # 检查是否已经发放过积分
        existing_points = PointTransaction.objects.filter(
            user=event.organizer,
            source_type='event_create',
            related_event=event,
            transaction_type='earn'
        )

        if existing_points.exists():
            print(f"⚠️ [积分发放] 该活动的积分已经发放过了")
            return JsonResponse({
                'success': True,
                'message': '该活动的积分已经发放过了',
                'points': existing_points.first().points
            })

        # 使用积分服务发放积分
        from Location.services import PointService

        # 直接调用积分服务的方法
        points = PointService.get_points_for_rule('event_create')
        print(f"🔍 [积分发放] 积分规则返回: {points} 积分")

        if points <= 0:
            return JsonResponse({
                'success': False,
                'message': '积分规则未配置或积分为0'
            })

        # 发放积分
        success, message = event.organizer.add_points(
            points,
            'event_create',
            f'活动发布奖励: {event.title}',
            related_event=event
        )

        if success:
            print(f"✅ [积分发放] 积分发放成功: {points} 积分")
            return JsonResponse({
                'success': True,
                'message': f'成功发放 {points} 积分给活动创建者',
                'points': points,
                'user_id': event.organizer.id,
                'new_points': event.organizer.points
            })
        else:
            print(f"❌ [积分发放] 积分发放失败: {message}")
            return JsonResponse({
                'success': False,
                'message': f'积分发放失败: {message}'
            })

    except Event.DoesNotExist:
        print(f"❌ [积分发放] 活动不存在: {event_id}")
        return JsonResponse({
            'success': False,
            'message': '活动不存在'
        })
    except Exception as e:
        print(f"❌ [积分发放] 异常: {str(e)}")
        import traceback
        traceback.print_exc()
        return JsonResponse({
            'success': False,
            'message': f'积分发放失败: {str(e)}'
        })
@require_http_methods(["GET"])
def dashboard_stats(request):
    """仪表板统计数据API"""
    if not request.user.is_superuser:
        return JsonResponse({'success': False, 'message': '权限不足'})

    try:
        # 计算今日日期
        today = timezone.now().date()

        # 基本统计数据
        total_users = CustomUser.objects.count()
        total_events = Event.objects.count()
        pending_events_count = Event.objects.filter(status='pending').count()

        # 今日数据
        today_users = CustomUser.objects.filter(date_joined__date=today).count()
        today_events = Event.objects.filter(created_at__date=today).count()

        # 活跃用户（最近7天有登录）
        week_ago = timezone.now() - timedelta(days=7)
        active_users = CustomUser.objects.filter(last_login__gte=week_ago).count()

        # 总积分（所有用户积分总和）
        total_points = CustomUser.objects.aggregate(total=Sum('points'))['total'] or 0

        # 商品总数（如果有商品模型）
        # total_rewards = Reward.objects.count()
        total_rewards = 23  # 暂时使用固定值

        # 最近活动（系统活动）
        recent_activities = [
            {
                'type': 'user_register',
                'title': '新用户注册',
                'time': '刚刚'
            },
            {
                'type': 'event_create',
                'title': '新活动创建',
                'time': '5分钟前'
            }
        ]

        # 最近注册用户
        recent_users = CustomUser.objects.order_by('-date_joined')[:5]
        recent_users_data = []
        for user in recent_users:
            recent_users_data.append({
                'username': user.username,
                'email': user.email,
                'avatar_url': user.avatar.url if user.avatar else 'https://via.placeholder.com/40',
                'join_time': '刚刚' if user.date_joined.date() == today else f'{user.date_joined.strftime("%H:%M")}'
            })

        # 最近创建的活动
        recent_events = Event.objects.order_by('-created_at')[:5]
        recent_events_data = []
        for event in recent_events:
            recent_events_data.append({
                'title': event.title,
                'organizer': event.organizer.username if event.organizer else '未知',
                'create_time': '刚刚' if event.created_at.date() == today else f'{event.created_at.strftime("%H:%M")}'
            })

        return JsonResponse({
            'success': True,
            'total_users': total_users,
            'total_events': total_events,
            'pending_events_count': pending_events_count,
            'today_users': today_users,
            'today_events': today_events,
            'active_users': active_users,
            'total_points': total_points,
            'total_rewards': total_rewards,
            'recent_activities': recent_activities,
            'recent_users': recent_users_data,
            'recent_events': recent_events_data
        })

    except Exception as e:
        return JsonResponse({'success': False, 'message': f'获取数据失败: {str(e)}'})
@user_passes_test(is_superuser)
def admin_event_approval(request):
    """活动审核 - 返回JSON数据"""
    pending_events = Event.objects.filter(status='pending').order_by('-created_at')

    events_data = []
    for event in pending_events:
        events_data.append({
            'id': event.id,
            'title': event.title,
            'description': event.description,
            'organizer': event.organizer.username,
            'start_time': event.start_time.strftime('%Y-%m-%d %H:%M'),
            'location': event.location,
            'current_participants': event.current_participants,
            'max_participants': event.max_participants,
            'created_at': event.created_at.strftime('%Y-%m-%d %H:%M')
        })

    return JsonResponse({'pending_events': events_data})


@user_passes_test(is_superuser)
def admin_user_management(request):
    """用户管理 - 返回JSON数据"""
    users = CustomUser.objects.all().order_by('-date_joined')

    users_data = []
    for user in users:
        users_data.append({
            'id': user.id,
            'username': user.username,
            'email': user.email,
            'date_joined': user.date_joined.strftime('%Y-%m-%d %H:%M'),
            'is_active': user.is_active,
            'is_superuser': user.is_superuser,
            'avatar_url': user.avatar.url if user.avatar and user.avatar.url else 'https://via.placeholder.com/40'
        })

    return JsonResponse({'users': users_data})


@user_passes_test(is_superuser)
def admin_event_management(request):
    """活动管理 - 返回JSON数据"""
    # 排除草稿状态的活动，只显示已发布、待审核、已拒绝、已取消的活动
    events = Event.objects.exclude(status='draft').order_by('-created_at')

    events_data = []
    for event in events:
        events_data.append({
            'id': event.id,
            'title': event.title,
            'organizer': event.organizer.username,
            'start_time': event.start_time.strftime('%Y-%m-%d %H:%M'),
            'location': event.location,
            'status': event.status,
            'status_display': event.get_status_display(),
            'current_participants': event.current_participants,
            'max_participants': event.max_participants,
            'created_at': event.created_at.strftime('%Y-%m-%d %H:%M')
        })

    return JsonResponse({'events': events_data})

@user_passes_test(is_superuser)
@require_POST
@csrf_exempt
def admin_approve_event(request, event_id):
    """批准活动"""
    try:
        event = Event.objects.get(id=event_id)
        event.status = 'published'
        event.save()

        return JsonResponse({'success': True, 'message': '活动已成功批准'})
    except Event.DoesNotExist:
        return JsonResponse({'success': False, 'message': '活动不存在'})
    except Exception as e:
        return JsonResponse({'success': False, 'message': f'操作失败: {str(e)}'})


@user_passes_test(is_superuser)
@require_POST
@csrf_exempt
def admin_reject_event(request, event_id):
    """拒绝活动"""
    try:
        event = Event.objects.get(id=event_id)
        event.status = 'rejected'
        event.save()

        return JsonResponse({'success': True, 'message': '活动已拒绝'})
    except Event.DoesNotExist:
        return JsonResponse({'success': False, 'message': '活动不存在'})
    except Exception as e:
        return JsonResponse({'success': False, 'message': f'操作失败: {str(e)}'})


@user_passes_test(is_superuser)
@require_POST
@csrf_exempt
def admin_delete_event(request, event_id):
    """删除活动"""
    try:
        event = Event.objects.get(id=event_id)
        event_title = event.title
        event.delete()

        return JsonResponse({'success': True, 'message': f'活动 "{event_title}" 已删除'})
    except Event.DoesNotExist:
        return JsonResponse({'success': False, 'message': '活动不存在'})
    except Exception as e:
        return JsonResponse({'success': False, 'message': f'删除失败: {str(e)}'})


@user_passes_test(is_superuser)
@require_POST
@csrf_exempt
def admin_toggle_user_status(request, user_id):
    """切换用户状态（启用/禁用）"""
    try:
        user = CustomUser.objects.get(id=user_id)
        user.is_active = not user.is_active
        user.save()

        status = "启用" if user.is_active else "禁用"
        return JsonResponse({'success': True, 'message': f'用户已{status}', 'is_active': user.is_active})
    except CustomUser.DoesNotExist:
        return JsonResponse({'success': False, 'message': '用户不存在'})
    except Exception as e:
        return JsonResponse({'success': False, 'message': f'操作失败: {str(e)}'})


@user_passes_test(is_superuser)
@require_POST
@csrf_exempt
def admin_delete_user(request, user_id):
    """删除用户"""
    try:
        user = CustomUser.objects.get(id=user_id)
        username = user.username

        # 不能删除自己
        if user == request.user:
            return JsonResponse({'success': False, 'message': '不能删除自己的账户'})

        user.delete()

        return JsonResponse({'success': True, 'message': f'用户 "{username}" 已删除'})
    except CustomUser.DoesNotExist:
        return JsonResponse({'success': False, 'message': '用户不存在'})
    except Exception as e:
        return JsonResponse({'success': False, 'message': f'删除失败: {str(e)}'})


@user_passes_test(is_superuser)
def view_event_details(request, event_id):
    """查看活动详情"""
    try:
        event = Event.objects.get(id=event_id)

        # 构建事件数据，使用模型中实际存在的字段
        event_data = {
            'id': event.id,
            'title': event.title,
            'description': event.description or '无描述',
            'organizer': event.organizer.username,
            'category': event.category.name if event.category else '未分类',
            'start_time': event.start_time.strftime('%Y-%m-%d %H:%M'),
            'end_time': event.end_time.strftime('%Y-%m-%d %H:%M') if event.end_time else '未设置',
            'registration_deadline': event.registration_deadline.strftime(
                '%Y-%m-%d %H:%M') if event.registration_deadline else '未设置',
            'location': event.location or '未设置地点',
            'location_details': event.location_details or '无详细地点信息',
            'max_participants': event.max_participants,
            'current_participants': event.current_participants,
            'status': event.status,
            'status_display': event.get_status_display(),
            'is_free': event.is_free,
            'fee': float(event.fee) if event.fee else 0.0,
            'views_count': event.views_count,
            'likes_count': event.likes_count,
            'created_at': event.created_at.strftime('%Y-%m-%d %H:%M'),
            'updated_at': event.updated_at.strftime('%Y-%m-%d %H:%M'),
        }

        return JsonResponse({'success': True, 'event': event_data})

    except Event.DoesNotExist:
        return JsonResponse({'success': False, 'message': '活动不存在'})
    except Exception as e:
        import traceback
        error_details = traceback.format_exc()
        print(f"获取活动详情错误: {str(e)}")
        print(error_details)
        return JsonResponse({'success': False, 'message': f'获取活动详情失败: {str(e)}'})


@user_passes_test(is_superuser)
@require_POST
@csrf_exempt
def admin_approve_event(request, event_id):
    """批准活动"""
    try:
        event = Event.objects.get(id=event_id)
        event.status = 'published'
        event.save()

        # 可以在这里添加通知逻辑
        return JsonResponse({'success': True, 'message': '活动已成功批准'})
    except Event.DoesNotExist:
        return JsonResponse({'success': False, 'message': '活动不存在'})
    except Exception as e:
        return JsonResponse({'success': False, 'message': f'操作失败: {str(e)}'})


@user_passes_test(is_superuser)
@require_POST
@csrf_exempt
def admin_reject_event(request, event_id):
    """拒绝活动"""
    try:
        event = Event.objects.get(id=event_id)
        event.status = 'rejected'
        event.save()

        return JsonResponse({'success': True, 'message': '活动已拒绝'})
    except Event.DoesNotExist:
        return JsonResponse({'success': False, 'message': '活动不存在'})
    except Exception as e:
        return JsonResponse({'success': False, 'message': f'操作失败: {str(e)}'})


@user_passes_test(is_superuser)
@require_POST
@csrf_exempt
def admin_delete_event(request, event_id):
    """安全删除活动"""
    try:
        event = Event.objects.get(id=event_id)
        event_title = event.title

        # 记录要删除的相关对象数量（用于调试）
        deleted_counts = {}

        # 安全地删除相关记录
        try:
            from Location.models import CommunityPost
            count, _ = CommunityPost.objects.filter(event=event).delete()
            deleted_counts['community_posts'] = count
        except Exception as e:
            print(f"删除社区帖子时出错: {str(e)}")

        try:
            count, _ = EventDiscussion.objects.filter(event=event).delete()
            deleted_counts['discussions'] = count
        except Exception as e:
            print(f"删除活动讨论时出错: {str(e)}")

        try:
            count, _ = EventReview.objects.filter(event=event).delete()
            deleted_counts['reviews'] = count
        except Exception as e:
            print(f"删除活动评价时出错: {str(e)}")

        try:
            count, _ = EventRegistration.objects.filter(event=event).delete()
            deleted_counts['registrations'] = count
        except Exception as e:
            print(f"删除活动报名记录时出错: {str(e)}")

        # 最后删除活动本身
        event.delete()

        message = f'活动 "{event_title}" 已删除'
        if deleted_counts:
            details = ', '.join([f'{v}个{k}' for k, v in deleted_counts.items() if v > 0])
            if details:
                message += f' (同时删除了 {details})'

        return JsonResponse({'success': True, 'message': message})
    except Event.DoesNotExist:
        return JsonResponse({'success': False, 'message': '活动不存在'})
    except Exception as e:
        # 提供更详细的错误信息
        error_msg = f'删除失败: {str(e)}'
        if 'foreign key constraint' in str(e).lower():
            error_msg += '。这可能是因为还有其他表引用了此活动。'
        return JsonResponse({'success': False, 'message': error_msg})

@user_passes_test(is_superuser)
@require_POST
@csrf_exempt
def admin_toggle_user_status(request, user_id):
    """切换用户状态（启用/禁用）"""
    try:
        user = CustomUser.objects.get(id=user_id)
        user.is_active = not user.is_active
        user.save()

        status = "启用" if user.is_active else "禁用"
        return JsonResponse({'success': True, 'message': f'用户已{status}', 'is_active': user.is_active})
    except CustomUser.DoesNotExist:
        return JsonResponse({'success': False, 'message': '用户不存在'})
    except Exception as e:
        return JsonResponse({'success': False, 'message': f'操作失败: {str(e)}'})


@user_passes_test(is_superuser)
@require_POST
@csrf_exempt
def admin_delete_user(request, user_id):
    """删除用户"""
    try:
        user = CustomUser.objects.get(id=user_id)
        username = user.username

        # 不能删除自己
        if user == request.user:
            return JsonResponse({'success': False, 'message': '不能删除自己的账户'})

        user.delete()

        return JsonResponse({'success': True, 'message': f'用户 "{username}" 已删除'})
    except CustomUser.DoesNotExist:
        return JsonResponse({'success': False, 'message': '用户不存在'})
    except Exception as e:
        return JsonResponse({'success': False, 'message': f'删除失败: {str(e)}'})

@login_required
def publish_draft(request, draft_id):
    """发布草稿为正式活动"""
    if request.method == 'POST' and request.headers.get('x-requested-with') == 'XMLHttpRequest':
        try:
            draft = Event.objects.get(
                id=draft_id,
                organizer=request.user,
                status='draft'
            )

            # 验证必填字段
            required_fields = ['title', 'description', 'start_time', 'location']
            missing_fields = []
            for field in required_fields:
                if not getattr(draft, field, None):
                    missing_fields.append(field)

            if missing_fields:
                return JsonResponse({
                    'success': False,
                    'message': f'请先完善活动信息，缺失字段: {", ".join(missing_fields)}'
                })

            # 将草稿转为待审核状态
            draft.status = 'pending'
            draft.save()

            return JsonResponse({
                'success': True,
                'message': '活动发布成功，等待审核',
                'redirect_url': reverse('customer:profile')
            })

        except Event.DoesNotExist:
            return JsonResponse({
                'success': False,
                'message': '草稿不存在或无权操作'
            })
        except Exception as e:
            return JsonResponse({
                'success': False,
                'message': f'发布失败：{str(e)}'
            })

    return JsonResponse({
        'success': False,
        'message': '无效的请求'
    })


@login_required
def delete_draft(request, draft_id):
    """删除草稿"""
    if request.method == 'POST' and request.headers.get('x-requested-with') == 'XMLHttpRequest':
        try:
            draft = Event.objects.get(
                id=draft_id,
                organizer=request.user,
                status='draft'
            )
            draft_title = draft.title or "未命名活动"

            # 删除相关图片
            draft.images.all().delete()

            # 删除草稿
            draft.delete()

            return JsonResponse({
                'success': True,
                'message': f'草稿 "{draft_title}" 已删除'
            })

        except Event.DoesNotExist:
            return JsonResponse({
                'success': False,
                'message': '草稿不存在或无权操作'
            })
        except Exception as e:
            return JsonResponse({
                'success': False,
                'message': f'删除失败：{str(e)}'
            })

    return JsonResponse({
        'success': False,
        'message': '无效的请求'
    })


from django.http import JsonResponse
from django.views.decorators.http import require_http_methods
from django.core.paginator import Paginator
from django.db.models import Q, Sum, Count
from django.utils import timezone
import json
from datetime import datetime, timedelta
from Customer.models import CustomUser
from Location.models import PointTransaction, PointRule


# 积分管理视图函数
@require_http_methods(["GET"])
def points_management(request):
    """积分管理主页面"""
    if not request.user.is_superuser:
        return JsonResponse({'success': False, 'message': '权限不足'})

    # 获取积分统计
    total_points = CustomUser.objects.aggregate(total=Sum('points'))['total'] or 0
    active_users = CustomUser.objects.filter(points__gt=0).count()
    today_records = PointTransaction.objects.filter(
        created_at__date=timezone.now().date()
    ).count()

    context = {
        'total_points': total_points,
        'active_users': active_users,
        'today_records': today_records,
    }
    return render(request, 'admin_dashboard.html', context)


@require_http_methods(["GET"])
def points_list_data(request):
    """获取积分列表数据"""
    if not request.user.is_superuser:
        return JsonResponse({'success': False, 'message': '权限不足'})

    # 获取查询参数
    page = int(request.GET.get('page', 1))
    limit = int(request.GET.get('limit', 10))
    username = request.GET.get('username', '')
    phone = request.GET.get('phone', '')
    source_type = request.GET.get('source_type', '')
    transaction_type = request.GET.get('transaction_type', '')
    start_time = request.GET.get('start_time', '')
    end_time = request.GET.get('end_time', '')

    # 构建查询条件
    records = PointTransaction.objects.select_related('user').all().order_by('-created_at')

    if username:
        records = records.filter(user__username__icontains=username)
    if phone:
        records = records.filter(user__phone__icontains=phone)
    if source_type:
        records = records.filter(source_type=source_type)
    if transaction_type:
        records = records.filter(transaction_type=transaction_type)
    if start_time:
        records = records.filter(created_at__gte=start_time)
    if end_time:
        records = records.filter(created_at__lte=end_time)

    # 分页
    paginator = Paginator(records, limit)
    page_obj = paginator.get_page(page)

    records_data = []
    for record in page_obj:
        # 获取相关对象信息
        related_info = ""
        if record.related_event:
            related_info = f"活动: {record.related_event.title}"
        elif record.related_post:
            related_info = f"帖子: {record.related_post.title}"

        records_data.append({
            'id': record.id,
            'username': record.user.username,
            'phone': record.user.phone,
            'points': record.points,
            'transaction_type': record.transaction_type,
            'transaction_type_display': record.get_transaction_type_display(),
            'source_type': record.source_type,
            'source_type_display': record.get_source_type_display(),
            'description': record.description,
            'related_info': related_info,
            'created_at': record.created_at.strftime('%Y-%m-%d %H:%M:%S'),
        })

    return JsonResponse({
        'success': True,
        'data': records_data,
        'total': paginator.count,
        'page': page,
        'limit': limit,
        'total_pages': paginator.num_pages,
    })


@require_http_methods(["GET"])
def user_points_detail(request, user_id):
    """获取用户积分详情"""
    if not request.user.is_superuser:
        return JsonResponse({'success': False, 'message': '权限不足'})

    try:
        user = CustomUser.objects.get(id=user_id)

        # 获取用户积分记录
        points_records = PointTransaction.objects.filter(user=user).order_by('-created_at')[:20]

        # 获取本月统计
        today = timezone.now()
        first_day = today.replace(day=1, hour=0, minute=0, second=0, microsecond=0)
        month_earned = PointTransaction.objects.filter(
            user=user,
            transaction_type='earn',
            created_at__gte=first_day
        ).aggregate(total=Sum('points'))['total'] or 0

        month_used = PointTransaction.objects.filter(
            user=user,
            transaction_type='spend',
            created_at__gte=first_day
        ).aggregate(total=Sum('points'))['total'] or 0

        # 获取总统计
        total_earned = PointTransaction.objects.filter(
            user=user,
            transaction_type='earn'
        ).aggregate(total=Sum('points'))['total'] or 0

        total_used = PointTransaction.objects.filter(
            user=user,
            transaction_type='spend'
        ).aggregate(total=Sum('points'))['total'] or 0

        records_data = []
        for record in points_records:
            records_data.append({
                'points': record.points,
                'transaction_type': record.get_transaction_type_display(),
                'source_type': record.get_source_type_display(),
                'description': record.description,
                'created_at': record.created_at.strftime('%Y-%m-%d %H:%M:%S'),
            })

        return JsonResponse({
            'success': True,
            'user': {
                'id': user.id,
                'username': user.username,
                'phone': user.phone,
                'email': user.email,
                'current_points': user.points,
                'total_points_earned': user.total_points_earned,
                'level': user.level,
                'experience': user.experience,
                'month_earned': month_earned,
                'month_used': month_used,
                'total_earned': total_earned,
                'total_used': total_used,
                'points_records': records_data,
            }
        })

    except CustomUser.DoesNotExist:
        return JsonResponse({'success': False, 'message': '用户不存在'})


@require_http_methods(["POST"])
def adjust_user_points(request):
    """调整用户积分"""
    if not request.user.is_superuser:
        return JsonResponse({'success': False, 'message': '权限不足'})

    try:
        data = json.loads(request.body)
        user_id = data.get('user_id')
        points = int(data.get('points', 0))
        remark = data.get('remark', '管理员调整')

        if not user_id or points == 0:
            return JsonResponse({'success': False, 'message': '参数错误'})

        user = CustomUser.objects.get(id=user_id)

        # 确定交易类型
        if points > 0:
            transaction_type = 'earn'
            description = f"管理员奖励: {remark}"
        else:
            transaction_type = 'spend'
            description = f"管理员扣除: {remark}"
            # 检查积分是否足够
            if user.points + points < 0:
                return JsonResponse({'success': False, 'message': '用户积分不足'})

        # 创建积分交易记录
        PointTransaction.objects.create(
            user=user,
            transaction_type=transaction_type,
            points=abs(points),
            source_type='system_bonus',
            description=description,
        )

        # 更新用户积分
        if transaction_type == 'earn':
            user.points += points
            user.total_points_earned += points
            user.experience += points
        else:
            user.points += points  # points为负数

        # 更新等级
        user.level = max(1, user.experience // 1000 + 1)
        user.save()

        return JsonResponse({
            'success': True,
            'message': f'成功调整用户积分: {points}',
            'new_points': user.points
        })

    except CustomUser.DoesNotExist:
        return JsonResponse({'success': False, 'message': '用户不存在'})
    except Exception as e:
        return JsonResponse({'success': False, 'message': f'调整失败: {str(e)}'})


@require_http_methods(["POST"])
def batch_adjust_points(request):
    """批量调整积分"""
    if not request.user.is_superuser:
        return JsonResponse({'success': False, 'message': '权限不足'})

    try:
        data = json.loads(request.body)
        user_ids = data.get('user_ids', [])
        points = int(data.get('points', 0))
        remark = data.get('remark', '批量调整')

        if not user_ids or points == 0:
            return JsonResponse({'success': False, 'message': '参数错误'})

        success_count = 0
        error_messages = []

        for user_id in user_ids:
            try:
                user = CustomUser.objects.get(id=user_id)

                # 确定交易类型
                if points > 0:
                    transaction_type = 'earn'
                    description = f"批量奖励: {remark}"
                else:
                    transaction_type = 'spend'
                    description = f"批量扣除: {remark}"
                    # 检查积分是否足够
                    if user.points + points < 0:
                        error_messages.append(f"用户 {user.username} 积分不足")
                        continue

                # 创建积分交易记录
                PointTransaction.objects.create(
                    user=user,
                    transaction_type=transaction_type,
                    points=abs(points),
                    source_type='system_bonus',
                    description=description,
                )

                # 更新用户积分
                if transaction_type == 'earn':
                    user.points += points
                    user.total_points_earned += points
                    user.experience += points
                else:
                    user.points += points  # points为负数

                # 更新等级
                user.level = max(1, user.experience // 1000 + 1)
                user.save()

                success_count += 1

            except CustomUser.DoesNotExist:
                error_messages.append(f"用户ID {user_id} 不存在")
            except Exception as e:
                error_messages.append(f"用户ID {user_id} 调整失败: {str(e)}")

        return JsonResponse({
            'success': True,
            'message': f'成功调整 {success_count} 个用户积分',
            'success_count': success_count,
            'error_count': len(error_messages),
            'error_messages': error_messages
        })

    except Exception as e:
        return JsonResponse({'success': False, 'message': f'批量调整失败: {str(e)}'})


@require_http_methods(["GET"])
def points_statistics(request):
    """积分统计"""
    if not request.user.is_superuser:
        return JsonResponse({'success': False, 'message': '权限不足'})

    # 时间范围
    start_time = request.GET.get('start_time')
    end_time = request.GET.get('end_time')

    # 基础查询
    records = PointTransaction.objects.all()

    if start_time:
        records = records.filter(created_at__gte=start_time)
    if end_time:
        records = records.filter(created_at__lte=end_time)

    # 统计信息
    total_points_issued = records.filter(transaction_type='earn').aggregate(
        total=Sum('points')
    )['total'] or 0

    total_points_used = records.filter(transaction_type='spend').aggregate(
        total=Sum('points')
    )['total'] or 0

    total_transactions = records.count()
    unique_users = records.values('user').distinct().count()

    # 来源类型分布
    source_type_distribution = records.values('source_type').annotate(
        count=Count('id'),
        total_points=Sum('points')
    )

    type_distribution = []
    for item in source_type_distribution:
        type_distribution.append({
            'source_type': item['source_type'],
            'source_type_display': dict(PointTransaction.SOURCE_TYPES).get(item['source_type'], '未知'),
            'count': item['count'],
            'total_points': item['total_points']
        })

    # 交易类型分布
    transaction_type_distribution = records.values('transaction_type').annotate(
        count=Count('id'),
        total_points=Sum('points')
    )

    transaction_distribution = []
    for item in transaction_type_distribution:
        transaction_distribution.append({
            'transaction_type': item['transaction_type'],
            'transaction_type_display': dict(PointTransaction.TRANSACTION_TYPES).get(item['transaction_type'], '未知'),
            'count': item['count'],
            'total_points': item['total_points']
        })

    # 最近7天趋势
    end_date = timezone.now().date()
    start_date = end_date - timedelta(days=6)

    daily_stats = []
    for i in range(7):
        date = start_date + timedelta(days=i)
        day_records = records.filter(created_at__date=date)

        day_earned = day_records.filter(transaction_type='earn').aggregate(
            total=Sum('points')
        )['total'] or 0

        day_used = day_records.filter(transaction_type='spend').aggregate(
            total=Sum('points')
        )['total'] or 0

        daily_stats.append({
            'date': date.strftime('%Y-%m-%d'),
            'earned': day_earned,
            'used': day_used,
            'transactions': day_records.count()
        })

    return JsonResponse({
        'success': True,
        'statistics': {
            'total_points_issued': total_points_issued,
            'total_points_used': total_points_used,
            'total_transactions': total_transactions,
            'unique_users': unique_users,
            'source_type_distribution': type_distribution,
            'transaction_type_distribution': transaction_distribution,
            'daily_stats': daily_stats,
        }
    })


@require_http_methods(["GET"])
def points_rules_management(request):
    """积分规则管理"""
    if not request.user.is_superuser:
        return JsonResponse({'success': False, 'message': '权限不足'})

    rules = PointRule.objects.all().order_by('rule_type')
    rules_data = []

    for rule in rules:
        rules_data.append({
            'id': rule.id,
            'rule_type': rule.rule_type,
            'rule_type_display': rule.get_rule_type_display(),
            'points': rule.points,
            'daily_limit': rule.daily_limit,
            'description': rule.description,
            'is_active': rule.is_active,
            'created_at': rule.created_at.strftime('%Y-%m-%d %H:%M:%S'),
        })

    return JsonResponse({
        'success': True,
        'rules': rules_data
    })


@require_http_methods(["POST"])
def update_points_rule(request, rule_id):
    """更新积分规则"""
    if not request.user.is_superuser:
        return JsonResponse({'success': False, 'message': '权限不足'})

    try:
        data = json.loads(request.body)
        rule = PointRule.objects.get(id=rule_id)

        if 'points' in data:
            rule.points = int(data['points'])
        if 'daily_limit' in data:
            rule.daily_limit = int(data['daily_limit'])
        if 'description' in data:
            rule.description = data['description']
        if 'is_active' in data:
            rule.is_active = bool(data['is_active'])

        rule.save()

        return JsonResponse({
            'success': True,
            'message': '积分规则更新成功'
        })

    except PointRule.DoesNotExist:
        return JsonResponse({'success': False, 'message': '积分规则不存在'})
    except Exception as e:
        return JsonResponse({'success': False, 'message': f'更新失败: {str(e)}'})


@require_http_methods(["GET"])
def export_points_data(request):
    """导出积分数据"""
    if not request.user.is_superuser:
        return JsonResponse({'success': False, 'message': '权限不足'})

    try:
        import csv
        from django.http import HttpResponse

        # 获取查询参数
        username = request.GET.get('username', '')
        phone = request.GET.get('phone', '')
        source_type = request.GET.get('source_type', '')
        transaction_type = request.GET.get('transaction_type', '')
        start_time = request.GET.get('start_time', '')
        end_time = request.GET.get('end_time', '')

        # 构建查询条件
        records = PointTransaction.objects.select_related('user').all().order_by('-created_at')

        if username:
            records = records.filter(user__username__icontains=username)
        if phone:
            records = records.filter(user__phone__icontains=phone)
        if source_type:
            records = records.filter(source_type=source_type)
        if transaction_type:
            records = records.filter(transaction_type=transaction_type)
        if start_time:
            records = records.filter(created_at__gte=start_time)
        if end_time:
            records = records.filter(created_at__lte=end_time)

        # 创建HTTP响应
        response = HttpResponse(content_type='text/csv')
        response[
            'Content-Disposition'] = f'attachment; filename="points_data_{timezone.now().strftime("%Y%m%d_%H%M%S")}.csv"'

        writer = csv.writer(response)
        # 写入表头
        writer.writerow(['用户名', '手机号', '积分数量', '交易类型', '来源类型', '描述', '相关活动/帖子', '创建时间'])

        # 写入数据
        for record in records:
            related_info = ""
            if record.related_event:
                related_info = f"活动: {record.related_event.title}"
            elif record.related_post:
                related_info = f"帖子: {record.related_post.title}"

            writer.writerow([
                record.user.username,
                record.user.phone,
                record.points,
                record.get_transaction_type_display(),
                record.get_source_type_display(),
                record.description,
                related_info,
                record.created_at.strftime('%Y-%m-%d %H:%M:%S')
            ])

        return response

    except Exception as e:
        return JsonResponse({'success': False, 'message': f'导出失败: {str(e)}'})


# ==================== 数据统计功能 ====================

@user_passes_test(is_superuser)
def admin_data_statistics(request):
    """数据统计视图 - 返回JSON数据"""
    try:
        # 用户统计
        total_users = CustomUser.objects.count()
        today_users = CustomUser.objects.filter(date_joined__date=timezone.now().date()).count()
        active_users_7d = CustomUser.objects.filter(last_login__gte=timezone.now() - timedelta(days=7)).count()
        active_users_30d = CustomUser.objects.filter(last_login__gte=timezone.now() - timedelta(days=30)).count()

        # 活动统计
        total_events = Event.objects.count()
        published_events = Event.objects.filter(status='published').count()
        pending_events = Event.objects.filter(status='pending').count()
        cancelled_events = Event.objects.filter(status='cancelled').count()

        # 积分统计
        total_points = CustomUser.objects.aggregate(total=Sum('points'))['total'] or 0
        points_issued = PointTransaction.objects.filter(transaction_type='earn').aggregate(total=Sum('points'))[
                            'total'] or 0
        points_used = PointTransaction.objects.filter(transaction_type='spend').aggregate(total=Sum('points'))[
                          'total'] or 0

        # 注册趋势（最近30天）
        end_date = timezone.now().date()
        start_date = end_date - timedelta(days=29)

        registration_trend = []
        for i in range(30):
            date = start_date + timedelta(days=i)
            count = CustomUser.objects.filter(date_joined__date=date).count()
            registration_trend.append({
                'date': date.strftime('%Y-%m-%d'),
                'count': count
            })

        # 活动创建趋势（最近30天）
        event_trend = []
        for i in range(30):
            date = start_date + timedelta(days=i)
            count = Event.objects.filter(created_at__date=date).count()
            event_trend.append({
                'date': date.strftime('%Y-%m-%d'),
                'count': count
            })

        # 用户等级分布
        level_distribution = []
        for level in range(1, 11):  # 假设最多10级
            count = CustomUser.objects.filter(level=level).count()
            if count > 0:
                level_distribution.append({
                    'level': f'Lv{level}',
                    'count': count
                })

        # 热门活动分类
        from django.db.models import Count
        category_stats = Event.objects.values('category__name').annotate(
            count=Count('id'),
            avg_participants=Avg('current_participants')
        ).order_by('-count')[:10]

        category_data = []
        for cat in category_stats:
            category_data.append({
                'name': cat['category__name'] or '未分类',
                'count': cat['count'],
                'avg_participants': round(cat['avg_participants'] or 0, 1)
            })

        return JsonResponse({
            'success': True,
            'statistics': {
                'users': {
                    'total': total_users,
                    'today': today_users,
                    'active_7d': active_users_7d,
                    'active_30d': active_users_30d
                },
                'events': {
                    'total': total_events,
                    'published': published_events,
                    'pending': pending_events,
                    'cancelled': cancelled_events
                },
                'points': {
                    'total': total_points,
                    'issued': points_issued,
                    'used': points_used
                },
                'trends': {
                    'registration': registration_trend,
                    'events': event_trend
                },
                'distributions': {
                    'levels': level_distribution,
                    'categories': category_data
                }
            }
        })

    except Exception as e:
        return JsonResponse({'success': False, 'message': f'获取统计数据失败: {str(e)}'})


# ==================== 系统设置功能 ====================

@user_passes_test(is_superuser)
def admin_system_settings(request):
    """系统设置视图 - 返回JSON数据"""
    try:
        # 获取当前系统设置（这里可以扩展从数据库或配置文件中读取）
        settings_data = {
            'site_name': '本地有约',
            'site_description': '本地活动社交平台',
            'admin_email': 'admin@localmeet.com',
            'max_file_size': 5,  # MB
            'allowed_file_types': ['jpg', 'jpeg', 'png', 'gif', 'webp'],
            'auto_approve_events': False,
            'points_enabled': True,
            'registration_open': True,
            'maintenance_mode': False,
            'cache_enabled': True,
            'backup_enabled': True
        }

        return JsonResponse({
            'success': True,
            'settings': settings_data
        })

    except Exception as e:
        return JsonResponse({'success': False, 'message': f'获取系统设置失败: {str(e)}'})


@user_passes_test(is_superuser)
@require_POST
@csrf_exempt
def admin_update_settings(request):
    """更新系统设置"""
    try:
        data = json.loads(request.body)

        # 这里可以实现将设置保存到数据库或配置文件的逻辑
        # 目前只是返回成功消息

        return JsonResponse({
            'success': True,
            'message': '系统设置已更新'
        })

    except Exception as e:
        return JsonResponse({'success': False, 'message': f'更新设置失败: {str(e)}'})


@user_passes_test(is_superuser)
@require_POST
@csrf_exempt
def admin_clear_cache(request):
    """清除系统缓存"""
    try:
        from django.core.cache import cache
        cache.clear()

        return JsonResponse({
            'success': True,
            'message': '系统缓存已清除'
        })

    except Exception as e:
        return JsonResponse({'success': False, 'message': f'清除缓存失败: {str(e)}'})


@user_passes_test(is_superuser)
@require_POST
@csrf_exempt
def admin_system_backup(request):
    """系统备份"""
    try:
        # 这里可以实现系统备份逻辑
        # 目前只是返回成功消息

        backup_time = timezone.now().strftime('%Y-%m-%d %H:%M:%S')

        return JsonResponse({
            'success': True,
            'message': f'系统备份已完成 ({backup_time})',
            'backup_time': backup_time
        })

    except Exception as e:
        return JsonResponse({'success': False, 'message': f'系统备份失败: {str(e)}'})